package com.example.intelglasses;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.sunflower.FlowerCollector;
import com.example.intelglasses.DBManager;

import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class QueryData extends Activity {

	static float paintscale = 1.0f;
	int screenwidth;
	static Boolean isch1able = false;
	static Boolean isch2able = false;
	static Boolean isch3able = false;
	static float mutinum = 2f;
	static float addOrSub=-190f;
	char[] buffer0;
	static char[] buffer1 = new char[101]; // CH1的数据接收buffer
	static char[] buffer2 = new char[101]; // CH2的数据接收buffer
	String ch1max, ch1min, ch1cha, ch2max, ch2min, ch2cha, ch1fhz, ch2fhz,
			axisX, axisY;
	char maxch1, maxch2, minch1, minch2;
	public String ipstring, portstring;

	private TextView statusText;
	private TextView multiText;
	private TextView textX;
	private TextView textY;
	private Button buttch1;
	private Button buttch2;
	private Button buttch3;
	private Button buttadd;
	private Button buttsub;
	private Button buttchange;
	private Button buttchange3;
	public Spinner spin1;
	private Vibrator vibrator;
	public MyView1 view1;
	private Spinner mSpinner;
	private ArrayAdapter<String> adapter;
	private DBManager mDbManager;
	private String[] mStrings;
	int dataQuantity;
	
	private ImageButton buttvoiceButton;
	// 语音听写对象
	private SpeechRecognizer mIat;
	// 语音听写UI
	private RecognizerDialog mIatDialog;
	// 用HashMap存储听写结果
	private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
	private Toast mToast;
	// 引擎类型
	private String mEngineType = SpeechConstant.TYPE_CLOUD;
	//printResult会发神经执行2次,所以立下flag砍掉1次
	private boolean firstFlag = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.query_main);
		statusText = (TextView) findViewById(R.id.textStatus2);
		multiText = (TextView) findViewById(R.id.textmulti2);
		view1 = (MyView1) findViewById(R.id.canvaslayout2);
		textX = (TextView) findViewById(R.id.textX2);
		textY = (TextView) findViewById(R.id.textY2);
		buttch1 = (Button) findViewById(R.id.ch1Butt2);
		buttch2 = (Button) findViewById(R.id.ch2Butt2);
		buttch3 = (Button) findViewById(R.id.ch3Butt2);
		buttadd = (Button) findViewById(R.id.addButt2);
		buttsub = (Button) findViewById(R.id.subButt2);
		buttchange = (Button) findViewById(R.id.buttcontext2);     //信号发生器
		buttchange3 = (Button) findViewById(R.id.buttcontext3);  //示波器
		buttvoiceButton = (ImageButton) findViewById(R.id.buttvoiceData);
		spin1 = (Spinner) findViewById(R.id.Spinner1);
		Display mdisplay = getWindowManager().getDefaultDisplay();
		screenwidth = mdisplay.getWidth();
		if (screenwidth == 720) {
			paintscale = 1.0f;
		}
		if (screenwidth == 1080) {
			paintscale = 1.5f;
		}
		ch1max = "??";
		ch1min = "??";
		ch1cha = "??";
		ch1fhz = "??";
		ch2max = "??";
		ch2min = "??";
		ch2cha = "??";
		ch2fhz = "??";
		axisX = "???";
		axisY = "???";

		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		vibrator.vibrate(20);
		buttch2.setText("CH2->开");
		isch2able = true;
		isch3able = true;
		buttch3.setText("CH1+2->开");
		// 数据库的操作开始
		mDbManager = new DBManager(this);
		List<String[]> strs = mDbManager.query();
		dataQuantity = strs.size();
		mStrings = new String[dataQuantity];

		for (int i = 0; i < dataQuantity; i++) {
			String[] resultStr = strs.get(i);
			mStrings[i] = resultStr[0];
		}
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.browser_link_context_header, mStrings);
		adapter.setDropDownViewResource(android.R.layout.preference_category);
		spin1.setAdapter(adapter);
		spin1.setOnItemSelectedListener(new MyOnItemSelectedListener());
		spin1.setVisibility(View.VISIBLE);
		Intent intent = getIntent();
		ipstring = intent.getStringExtra("ipstring");
		portstring = intent.getStringExtra("portint");
		
		// 初始化识别对象
		mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
		// 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
		mIatDialog = new RecognizerDialog(QueryData.this, mInitListener);
		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		mEngineType = SpeechConstant.TYPE_CLOUD;
	}
	/**
	 * 初始化监听器。
	 */
	private InitListener mInitListener = new InitListener() {

		@Override
		public void onInit(int code) {
			if (code != ErrorCode.SUCCESS) {
				showTip("初始化失败，错误码：" + code);
			}
		}
	};
	/**
	 * 听写监听器。
	 */
	private RecognizerListener recognizerListener = new RecognizerListener() {

		@Override
		public void onBeginOfSpeech() {
			showTip("开始说话");
		}

		@Override
		public void onError(SpeechError error) {
			// Tips：
			// 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
			// 如果使用本地功能（语音+）需要提示用户开启语音+的录音权限。
			showTip(error.getPlainDescription(true));
		}

		@Override
		public void onEndOfSpeech() {
			showTip("结束说话");
		}

		@Override
		public void onResult(RecognizerResult results, boolean isLast) {
			// printResult(results);

			if (isLast) {
			}
		}

		@Override
		public void onVolumeChanged(int volume) {
			showTip("当前正在说话，音量大小：" + volume);
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
		}
	};

	private void printResult(RecognizerResult results) {
		if(firstFlag==true)
		{
			firstFlag=false;
		String text = JsonParser.parseIatResult(results.getResultString());
		String sn = null;
		// 读取json结果中的sn字段
		try {
			JSONObject resultJson = new JSONObject(results.getResultString());
			sn = resultJson.optString("sn");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mIatResults.put(sn, text);

		StringBuffer resultBuffer = new StringBuffer();
		for (String key : mIatResults.keySet()) {
			resultBuffer.append(mIatResults.get(key));
		} 
		switch (JudgeVoice.returnQuery(resultBuffer.toString())) {
		case 1:
			buttchange.performClick();
			break;
		case 2:
			buttchange3.performClick();
			break;
		case 11:
			this.finish();
			break;
		case 21:
			buttch1.performClick();
			break;
		case 22:
			buttch2.performClick();
			break;
		case 0:
			Toast.makeText(QueryData.this, "识别不出来呀~~~", Toast.LENGTH_LONG)
			.show();
			break;
		default:
			break;
		}
		}
		else
		{
			firstFlag=true;
		}

	}

	/**
	 * 听写UI监听器
	 */
	private RecognizerDialogListener recognizerDialogListener = new RecognizerDialogListener() {
		public void onResult(RecognizerResult results, boolean isLast) {
			printResult(results);
		}

		/**
		 * 识别回调错误.
		 */
		public void onError(SpeechError error) {
			showTip(error.getPlainDescription(true));
		}

	};

	private void showTip(final String str) {
		mToast.setText(str);
		mToast.show();
	}
	/**
	 * 参数设置
	 * 
	 * @param param
	 * @return
	 */
	public void setParam() {
		// 清空参数
		mIat.setParameter(SpeechConstant.PARAMS, null);

		// 设置听写引擎
		mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
		// 设置返回结果格式
		mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
		String lag = "zh_cn";
		if (lag.equals("en_us")) {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
		} else {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
			// 设置语言区域
			mIat.setParameter(SpeechConstant.ACCENT, lag);
		}
		// 设置语音前端点
		mIat.setParameter(SpeechConstant.VAD_BOS, "4000");
		// 设置语音后端点
		mIat.setParameter(SpeechConstant.VAD_EOS, "1000");
		// 设置标点符号
		mIat.setParameter(SpeechConstant.ASR_PTT, "0");
		// 设置音频保存路径
		mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,
				Environment.getExternalStorageDirectory()
						+ "/iflytek/wavaudio.pcm");
		// 设置听写结果是否结果动态修正，为“1”则在听写过程中动态递增地返回结果，否则只在听写结束之后返回最终结果
		// 注：该参数暂时只对在线听写有效
		mIat.setParameter(SpeechConstant.ASR_DWA, "0");
	}

	@Override
	protected void onResume() {
		// 移动数据统计分析
		FlowerCollector.onResume(QueryData.this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		// 移动数据统计分析
		FlowerCollector.onPause(QueryData.this);
		super.onPause();
	}

	int ret = 0;
	/** 声控 */
	public void voiceActriveData(View sourve) {
		mIatResults.clear();
		setParam();
		boolean isShowDialog = true;
		if (isShowDialog) {
			// 显示听写对话框
			mIatDialog.setListener(recognizerDialogListener);
			mIatDialog.show();
			showTip(getString(R.string.text_begin));
		} else {
			// 不显示听写对话框
			mIatDialog.setListener(recognizerDialogListener);
			ret = mIat.startListening(recognizerListener);
			if (ret != ErrorCode.SUCCESS) {
				showTip("听写失败,错误码：" + ret);
			} else {
				showTip(getString(R.string.text_begin));
			}
		}
	}

	public void clickedch11(View sourve) {

		if (isch1able == false) {
			isch1able = true;
			buttch1.setText("CH1->开");
			vibrator.vibrate(20); // 震动20ms
			view1.invalidate();
		} else {
			isch1able = false;
			buttch1.setText("CH1->关");
			vibrator.vibrate(20); // 震动20ms
			view1.invalidate();
		}
	}

	public void clickedch22(View sourve) {

		if (isch2able == false) {
			isch2able = true;
			buttch2.setText("CH2->开");
			vibrator.vibrate(20); // 震动20ms
			view1.invalidate();

		} else {
			isch2able = false;
			buttch2.setText("CH2->关");
			vibrator.vibrate(20); // 震动20ms
			view1.invalidate();

		}

	}

	public void clickedch33(View sourve) {

		if (isch3able == false) {
			isch3able = true;
			buttch3.setText("CH1+2->开");
			view1.invalidate();
			vibrator.vibrate(20); // 震动20ms
		} else {
			isch3able = false;
			buttch3.setText("CH1+2->关");
			view1.invalidate();
			vibrator.vibrate(20); // 震动20ms
		}

	}

	public void clickedadd2(View sourve) {

		if (addOrSub <= 600f) {
			addOrSub += 5f;
			view1.invalidate();
			vibrator.vibrate(10); // 震动20ms
		}
	}

	public void clickedsub2(View sourve) {

		if (addOrSub >= (-600f)) {
			addOrSub -= 5f;
			view1.invalidate();
			vibrator.vibrate(10); // 震动20ms
		}

	}

	public void clickedmulti11(View sourve) {

		if (mutinum <= 10f) {
			mutinum += 0.5f;
			updateString();
			view1.invalidate();
			vibrator.vibrate(10); // 震动20ms
			multiText.setText("  波形缩放倍率: " + String.valueOf(mutinum));
		}

	}

	public void clickedmulti22(View sourve) {

		if (mutinum > 1f) {
			mutinum -= 0.5f;
			updateString();
			view1.invalidate();
			vibrator.vibrate(10); // 震动20ms
			multiText.setText("  波形缩放倍率: " + String.valueOf(mutinum));
		}
	}

	/** 切换模式的按钮 */
	public void changtocontext2(View sourve) {
		Intent intent = new Intent();
		intent.setClass(QueryData.this, generator.class);
		intent.putExtra("ipstring", ipstring);
		intent.putExtra("portint", portstring);
		startActivity(intent);
		QueryData.this.finish();
	}

	public void changtocontext3(View sourve) {
		Intent intent = new Intent();
		intent.setClass(QueryData.this, MainActivity.class);
		startActivity(intent);
		QueryData.this.finish();
	}

	public void onDestroy() {
		super.onDestroy();
		try {
			mDbManager.db.close();
		} catch (Exception e) {
			Toast.makeText(QueryData.this, "数据库关闭失败", Toast.LENGTH_LONG).show();
		}
	}

	/** Spinner监听接口 */
	class MyOnItemSelectedListener implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			Cursor cursor = mDbManager.db.rawQuery(
					"select * from mydata order by date desc", null);
			cursor.moveToPosition(position); // 数据库指针指向指定行
			String strtempch1 = cursor.getString(cursor.getColumnIndex("ch1")); // 获取指定列的内容
			String strtempch2 = cursor.getString(cursor.getColumnIndex("ch2")); // 获取指定列的内容
			String strtempbuffer1 = cursor.getString(cursor
					.getColumnIndex("buffer1")); // 获取指定列的内容
			String strtempbuffer2 = cursor.getString(cursor
					.getColumnIndex("buffer2")); // 获取指定列的内容
			buffer1 = strtempbuffer1.toCharArray();
			buffer2 = strtempbuffer2.toCharArray();
			cursor.close();
			ch1max = strtempch1.substring(0, 3);
			ch1min = strtempch1.substring(3, 6);
			ch1cha = strtempch1.substring(6, 9);
			ch1fhz = strtempch1.substring(9);
			ch2max = strtempch2.substring(0, 3);
			ch2min = strtempch2.substring(3, 6);
			ch2cha = strtempch2.substring(6, 9);
			ch2fhz = strtempch2.substring(9);
			updateString();
			statusText.setText("正常");
			view1.invalidate();
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}

	}

	/** 更新CH1和CH2的最大值最小值频率差值等等 */
	public void updateString() {
		axisX="150";
		// (float)(Math.round(QueryData.mutinum*0.1)*100))/100;
		axisY =String.valueOf(((float)(Math.round(QueryData.mutinum*0.1*100))/100));
		ch1fhz="3300";
		ch2fhz="1650";
		textX.setText("X轴每格:" + axisX + "us   CH1的频率:" + ch1fhz + "Hz\n"
				+ " CH1最大:" + ch1max + "V" + "  CH1最小:" + ch1min + "V"
				+ "  CH1电压差值:" + ch1cha + "V");
		textY.setText("Y轴每格:" + axisY + "V   CH2的频率:" + ch2fhz + "Hz\n"
				+ " CH2最大:" + ch2max + "V" + "  CH2最小:" + ch2min + "V"
				+ "  CH2电压差值:" + ch2cha + "V");
	}
}

/*************** 波形图系列 ***************/
class MyView1 extends View {

	Path path1, path2, path3;
	public char flagfirst = 0;

	public MyView1(Context context, AttributeSet set) {
		super(context, set);
		path1 = new Path();
		path2 = new Path();
		path3 = new Path();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (flagfirst != 2) {
			Paint paint = new Paint();
			paint.setAntiAlias(true);
			paint.setColor(Color.WHITE);
			paint.setStyle(Paint.Style.STROKE);
			paint.setStrokeWidth(1);
			// 画网格
			for (int i1 = 0; i1 < 21; i1++) {
				canvas.drawLine(0, 0, 0, 540 * QueryData.paintscale, paint);
				canvas.translate(30 * QueryData.paintscale, 0);
			}
			canvas.translate(-630 * QueryData.paintscale, 0);
			for (int i1 = 0; i1 < 19; i1++) {
				canvas.drawLine(0, 0, 600 * QueryData.paintscale, 0, paint);
				canvas.translate(0, 30 * QueryData.paintscale);
			}
			canvas.translate(0, -570 * QueryData.paintscale);
			paint.setStrokeWidth(2);
			// 画坐标
			canvas.drawText("0", 5 * QueryData.paintscale,
					270 * QueryData.paintscale, paint);
			paint.setStrokeWidth(4);
			// 画XY轴
			canvas.drawLine(0, 0, 0, 540 * QueryData.paintscale, paint);
			canvas.drawLine(0, 270 * QueryData.paintscale,
					600 * QueryData.paintscale, 270 * QueryData.paintscale,
					paint);
			// 画Path1
			path1.moveTo(
					0,
					(float) ((QueryData.buffer1[1]) * QueryData.mutinum * (-1)
							* QueryData.paintscale + 270 * QueryData.paintscale - QueryData.addOrSub));
			for (int i = 2; i <= 100; i++) {
				path1.lineTo((float) ((i - 1) * 6 * QueryData.paintscale),
						(float) ((QueryData.buffer1[i]) * QueryData.mutinum
								* (-1) * QueryData.paintscale + 270
								* QueryData.paintscale - QueryData.addOrSub));
			}
			paint.setPathEffect(null);
			paint.setColor(Color.GREEN);
			if (QueryData.isch1able == false) {
				canvas.drawPath(path1, paint);
			}
			path1.reset();
			// 画Path2
			path2.moveTo(
					0,
					(float) ((QueryData.buffer2[1]) * QueryData.mutinum * (-1)
							* QueryData.paintscale + 270 * QueryData.paintscale - QueryData.addOrSub));
			for (int i = 2; i <= 100; i++) {
				path2.lineTo((float) ((i - 1) * 6 * QueryData.paintscale),
						(float) ((QueryData.buffer2[i]) * QueryData.mutinum
								* (-1) * QueryData.paintscale + 270
								* QueryData.paintscale - QueryData.addOrSub));
			}
			paint.setPathEffect(null);
			paint.setColor(Color.RED);
			if (QueryData.isch2able == false) {
				canvas.drawPath(path2, paint);
			}
			path2.reset();
			// 画Path3
			path3.moveTo(0,
					(float) (((QueryData.buffer2[1] + QueryData.buffer1[1]))
							* QueryData.mutinum * (-1) * QueryData.paintscale
							+ 270 * QueryData.paintscale - QueryData.addOrSub));
			for (int i = 2; i <= 100; i++) {
				path3.lineTo(
						(float) ((i - 1) * 6 * QueryData.paintscale),
						(float) (((QueryData.buffer2[i]) + (QueryData.buffer1[i]))
								* QueryData.mutinum
								* (-1)
								* QueryData.paintscale
								+ 270
								* QueryData.paintscale - QueryData.addOrSub));
			}
			paint.setPathEffect(null);
			paint.setColor(Color.YELLOW);
			if (QueryData.isch3able == false) {
				canvas.drawPath(path3, paint);
			}
			path3.reset();
		}
		flagfirst = 1;
	}
}